<?php
/**
 * Introduction: 购物车逻辑
 * @author: 王龙
 * @date: 2016/4/13 13:07
 * @email: wanglong@cdlinglu.com
 */
namespace Common\Logic;

use Common\Model;

class CartLogic
{

    static public $model;

    public function __construct()
    {

        self::$model = new Model\CartModel();
    }

    /**
     * @introduction: 获取购物车数据
     * @author: 王龙
     * @email: wanglong@cdlinglu.com
     * @param array $where 查询条件
     * @param string $limit 分页
     * @return array
     */
    static public function getData($where, $fields = '*')
    {

        if(!$where['uid'])
            return ['code' => 500, 'msg' => '请登录!'];

        if (!$where)
            return ['code' => 300, 'msg' => '缺少购物车信息!'];

        $data = self::$model
            ->where($where)
            ->field($fields)
            ->select();

        if (!$data)
            return ['code' => 200, 'msg' => '暂无数据!'];

        $data = array_filter($data);

        if(!$data)
            $data = [];

        return ['code' => 200, 'data' => $data];


    }

    /**
     * @introduction: 获取商品数据
     * @author: 王龙
     * @email: wanglong@cdlinglu.com
     * @param array $where 查询条件
     * @param string $limit 分页
     * @return array
     */
    static public function getGoodsData($where, $order = 'created desc', $page, $nums = 20)
    {

        //获取商品ID


        if (!$where['uid'])
            return ['code' => 500, 'msg' => '请登录!'];

        $cart_info = self::$model
            ->where($where)
            ->order($order)
            ->field('id,goods_id,goods_num,goods_attr_val_ids')
            ->page($page, $nums)
            ->select();

        if (!$cart_info)
            return ['code' => 200, 'msg' => '您的购物车还是空的哦!'];

        $attr_logic = D('Common/Attr', 'Logic');


        foreach ($cart_info as $k => $v) {

            $attr = '';

            if ($v['goods_attr_val_ids']) {

                $attr_val_ids = trim($v['goods_attr_val_ids'], ',');

                $attr_val_info = $attr_logic::$model_attr_val
                    //->fetchSql(true)
                    ->where("id IN($attr_val_ids)")
                    ->field('name')
                    ->select();

                foreach ($attr_val_info as $v) {

                    $attr .= $v['name'] . ' ';

                }

                $cart_info[$k]['attr'] = $attr;

            }

        }

        $goods_logic = D('Common/Goods', 'Logic');

        //$fields = 'id,title,thumb,description,goods_salenum';

        $goods_info = [];


        foreach ($cart_info as $k => $v) {

            $whr = "extend.is_default = 1";

            if ($v['goods_attr_val_ids'])
                $whr = "extend.goods_attr_val_ids = '" . $v['goods_attr_val_ids'] . "'";

            $fileds = "'{$v['attr']}' as attr,{$v['id']} as cart_id, {$v['goods_num']} as goods_num,goods.title,extend.goods_id,extend.thumb,extend.goods_price,extend.goods_storage,extend.goods_attr_val_ids";

            $goods_info[] = $goods_logic::$model
                ->alias('goods')
                //->fetchSql(true)
                ->join('__GOODS_EXTEND__ extend ON goods.id = extend.goods_id', 'LEFT')
                ->where("goods.id = " . $v['goods_id'] . " AND $whr")
                ->field($fileds)
                ->find();

        }

        if (!$goods_info)
            return ['code' => 200, 'msg' => '没有商品！'];


        return ['code' => 200, 'data' => $goods_info];
    }

    /**
     * @introduction: 向购物车添加商品
     * @author: 王龙
     * @email: wanglong@cdlinglu.com
     * @param array $data 插入的数据
     * @notice:  杨陈鹏   2016/04/18 19:37  修改
     */
    static public function create($data,$uid)
    {


        if (!intval($data['goods_id']))
            return ['code' => 300, 'msg' => '商品ID不能为空'];

        if (!intval($data['goods_num']))
            return ['code' => 300, 'msg' => '商品数量不能为空!'];

        $order_logic = D('Common/Order','Logic');

        $res = $order_logic::checkGoodsStates($data['goods_id']);

        if(!$res)
            return ['code' => 300,'msg' => '当前商品已下架!'];


        $where['goods_id'] = $data['goods_id'];
        $where['goods_num'] = $data['goods_num'];

        if ($data['goods_attr_val_ids'])
            $where['goods_attr_val_ids'] = $data['goods_attr_val_ids'];

        //检测库存
        $check = self::checkStorage($where, true);

        if ($check['code'] == 300)
            return $check;

        unset($where['goods_num']);
        //检测该商品是否已经存在购物车中，则直接添加该商品的数量

        $where['uid'] = $uid;
        if ($result = self::$model->where($where)->field('id')->find()) {

            if (self::$model->where($where)->setInc('goods_num', $data['goods_num']))
                return ['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $result['id']]];

        } else {

            $data['created'] = NOW_TIME;

            if ($id = self::$model->add($data))
                return ['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $id]];

        }

        return ['code' => 300, 'msg' => '添加购物车失败!'];
    }

    /**
     * @introduction: 更新购物车里的数据
     * @author: 王龙
     * @email: wanglong@cdlinglu.com
     * @param array $data 数据 条件
     * @notice:  杨陈鹏   2016/04/18 19:37  修改
     */
    static public function update($data = array())
    {

        if (!$data)
            return ['code' => 300, 'msg' => '参数错误!'];

        $where['id'] = $data['id'];

        $where['uid'] = $data['uid'];

        $where['goods_num'] = $data['goods_nums'];

        //检测库存
        $check = self::checkStorage($where, false);

        //检测商品是否下架
        $goods_id = self::$model->where(['id' => $data['id']])->getField('goods_id');

        $order_logic = D('Common/Order','Logic');

        $res = $order_logic::checkGoodsStates($goods_id);

        if(!$res)
            return ['code' => 300,'msg' => '当前商品已下架!'];


        if ($check['code'] == 300)
            return $check;

        unset($where['goods_num']);

        //return self::$model->fetchSql(true)->where($where)->save(['goods_num' => $data['goods_nums']]);

        if (self::$model->where($where)->save(['goods_num' => $data['goods_nums']]) === false)
            return ['code' => 300, 'msg' => '更新失败'];

        return ['code' => 200, 'msg' => '更新成功'];


    }

    /**
     * @introduction: 移除购物车里的某种商品
     * @author: 王龙
     * @email: wanglong@cdlinglu.com
     * @param string $ids 条件  购物车ID    逗号隔开
     * @param int $uid 用户ID
     * @notice:  杨陈鹏   2016/04/18 19:37  修改
     */
    static public function delete($ids, $uid)
    {

        if (!$ids || !$uid)
            return ['code' => 500, 'msg' => '请登录!'];

        $ids = trim($ids, ',');

        if (self::$model->where("id IN($ids) AND uid = " . $uid)->delete())
            return ['code' => 200, 'msg' => '移除成功！'];


        return ['code' => 300, 'msg' => '移除失败！'];
    }

    /**
     * @introduction: 检测库存
     * @author: 杨陈鹏
     * @email: wanglong@cdlinglu.com
     * @param array $where 条件
     * @param bool $type true为添加时检测,  false为修改时检测
     * @return
     */
    static public function checkStorage($where, $type = true)
    {


        $goods_logic = D('Common/Goods', 'Logic');


        if ($type) {


            if (!intval($where['goods_id']))
                return ['code' => 300, 'msg' => '商品ID不能为空!'];

            if (!intval($where['goods_num']))
                return ['code' => 300, 'msg' => '商品数量不能为空!'];


            $cart_where['goods_id'] = $where['goods_id'];
            $cart_where['uid'] = $where['uid'];

            if (!$where['goods_attr_val_ids']) {

                $where['is_default'] = 1;
                $cart_where['goods_attr_val_ids'] = $where['goods_attr_val_ids'];

            }

            //获取购物车里面的商品数量
            $goods_nums = self::$model->where($cart_where)->getField('goods_num');

            unset($where['uid']);
            //获取商品库存
            $goods_storage = $goods_logic::$extend->where($where)->getField('goods_storage');

            if (intval($goods_storage) < (intval($where['goods_num']) + intval($goods_nums)))
                return ['code' => 300, 'msg' => '库存不足!'];

            return ['code' => 200];

        } else {
            if (!$where['id'])
                return ['code' => 300, 'msg' => '购物车商品ID不能为空!'];

            if (!$where['goods_num'])
                return ['code' => 300, 'msg' => '商品数量不能为空!'];

            //获取
            $cart_info = self::$model
                ->where(['id' => $where['id'], 'uid' => $where['uid']])
                ->field('goods_num,goods_attr_val_ids,goods_id')
                ->find();

            $where['goods_id'] = $cart_info['goods_id'];

            if ($cart_info['goods_attr_val_ids']) {

                $where['goods_attr_val_ids'] = $cart_info['goods_attr_val_ids'];

            } else {

                $where['is_default'] = 1;
            }


            $goods_num = $where['goods_num'];

            unset($where['uid']);
            unset($where['id']);
            unset($where['goods_num']);
            $goods_storage = $goods_logic::$extend->where($where)->getField('goods_storage');

            //if(intval($goods_storage) < (intval($goods_num) + intval($cart_info['goods_num'])))
            if (intval($goods_storage) < intval($goods_num))
                return ['code' => 300, 'msg' => '库存不足!'];

            return ['code' => 200];

        }


    }

}